package snsdbook.engine;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.concurrent.BlockingQueue;

import snsdbook.engine.message.MessageInterface;
import util.Util;

public class RequestHandler implements Runnable {

  public RequestHandler(BlockingQueue<Socket> sockets) {
    sockets_ = sockets;
  }
  
  @Override
  public void run() {
    while (true) {
      try {
        Socket sock = sockets_.take();
        Handle(sock);
      } catch (InterruptedException e) {
        // We don't like to be interrupted.
        continue;
      }
    }
  }
  
  private BlockingQueue<Socket> sockets_;
  
  private void Handle(Socket socket) {
    Util.Log("Received Socket connection from " + socket.getInetAddress());
    try {
      ObjectInputStream is = new ObjectInputStream(socket.getInputStream());
      ObjectOutputStream os = new ObjectOutputStream(socket.getOutputStream());
      Util.Log("Attempting to read message...");
      MessageInterface request = (MessageInterface)is.readObject();
      Util.Log("Message received = " + request.toString());
      request.ProcessAsServer(is, os);
      socket.close();
    } catch (Exception e) {
      Util.Warning(e);
    } catch (AbortError e) {
      Util.Warning("Aborted");
    }
  }

}
